﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Work.API.Applications.Read.Commands;
using Work.API.Dtos;
using Work.ErrorCode;
using Work.Infrastructure.Interfaces;

namespace Work.API.Applications.Read.CommandHandlers
{
    /// <summary>
    /// 获取患者账单处理器
    /// </summary>
    public class GetPatientBillQueryHandler : IRequestHandler<GetPatientBillQuery, ApiResult<PatientBillDto>>
    {
        private readonly IBaseRepository<Domain.Appintment> _appointmentRepo;
        private readonly IBaseRepository<Domain.Patient> _patientRepo;
        private readonly IMapper _mapper;

        public GetPatientBillQueryHandler(
            IBaseRepository<Domain.Appintment> appointmentRepo,
            IBaseRepository<Domain.Patient> patientRepo,
            IMapper mapper)
        {
            _appointmentRepo = appointmentRepo;
            _patientRepo = patientRepo;
            _mapper = mapper;
        }

        public async Task<ApiResult<PatientBillDto>> Handle(GetPatientBillQuery request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<PatientBillDto>();

            try
            {
                Domain.Appintment? appointment = null;

                // 根据不同的查询条件查找预约
                if (request.AppointmentId.HasValue && request.AppointmentId.Value > 0)
                {
                    appointment = await _appointmentRepo.GetById(request.AppointmentId.Value);
                }
                else if (!string.IsNullOrWhiteSpace(request.RegistrationNum))
                {
                    appointment = await _appointmentRepo.GetAll()
                        .FirstOrDefaultAsync(a => a.RegistrationNum == request.RegistrationNum, cancellationToken);
                }
                else if (!string.IsNullOrWhiteSpace(request.IdCard))
                {
                    var foundPatient = await _patientRepo.GetAll()
                        .FirstOrDefaultAsync(p => p.IdCard == request.IdCard, cancellationToken);
                    
                    if (foundPatient != null)
                    {
                        appointment = await _appointmentRepo.GetAll()
                            .Where(a => a.PatientId == foundPatient.PatientId)
                            .OrderByDescending(a => a.RegistrationDate)
                            .FirstOrDefaultAsync(cancellationToken);
                    }
                }

                if (appointment == null)
                {
                    result.Code = ApiEnum.失败;
                    result.Message = "未找到预约记录";
                    result.Data = null!;
                    return result;
                }

                // 获取患者信息
                var patient = await _patientRepo.GetById(appointment.PatientId);
                if (patient == null)
                {
                    result.Code = ApiEnum.失败;
                    result.Message = "未找到患者信息";
                    result.Data = null!;
                    return result;
                }

                // 构建账单DTO
                var bill = new PatientBillDto
                {
                    AppointmentId = appointment.AppintmentId,
                    PatientId = patient.PatientId,
                    PatientName = patient.PatientName,
                    GenderText = patient.Gender ? "男" : "女",
                    IdCard = patient.IdCard,
                    CardNumber = patient.CardNumber,
                    Department = appointment.Department,
                    DoctorName = appointment.DoctorName,
                    RegistrationNum = appointment.RegistrationNum
                };

                result.Code = ApiEnum.成功;
                result.Message = "查询成功";
                result.Data = bill;
            }
            catch (System.Exception ex)
            {
                result.Code = ApiEnum.失败;
                result.Message = $"查询失败：{ex.Message}";
                result.Data = null!;
            }

            return result;
        }
    }
}

